package com.wing.api.add.user.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wing.api.ApplicationContextUtil;
import com.wing.api.add.user.BaseUserService;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.common.constant.SapUtils;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.RSAUtils;
import com.wing.common.utils.Result;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.DepartmentForm;
import com.wing.user.model.request.Role;
import com.wing.user.model.request.User;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.user.model.response.DepartmentVO;
import com.wing.user.model.response.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 标准用户接口
 */
@Service
@Slf4j
public class E0524StandardUserServiceImpl implements BaseUserService {
    @Override
    public void logicProcess(JSONObject jsonObject, EnterpricceIdVO enterpricceIdVo) throws IOException {
        log.info("请求参数,{}", jsonObject.toJSONString());
        //此处需要做接口签名验证
        //sign = md5（参数1+参数2+参数3+key）
        String sourceSign = jsonObject.getString("sign"); // 签名值
        JSONArray data = jsonObject.getJSONArray("data"); //业务数据
        if(StringUtils.isBlank(sourceSign)){
            throw new BusinessException("签名值为空！");
        }
        if(StringUtils.isBlank(data.toJSONString())){
            throw new BusinessException("请求参数为空！");
        }
        log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex("companyName" +"departmentName" +"postName" +"username"+ enterpricceIdVo.getKey());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }
        UserClient userClient = (UserClient) ApplicationContextUtil.getBean("userClientFallback");
        //业务逻辑
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObj = data.getJSONObject(i);
            String companyName = jsonObj.getString("companyName");
            if(StringUtils.isEmpty(companyName)){
                throw new BusinessException("第" + (i+1) +  "所属企业不能为空！");
            }
            JsonResult<CompanyInfoVO> companyJsonResult = userClient.getCompanyByName(companyName);
            if(companyJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) +"当前企业不存在，请先同步企业数据！");
            }
            String departmentName = jsonObj.getString("departmentName");
            if(StringUtils.isEmpty(departmentName)){
                throw new BusinessException("第" + (i+1) +  "行部门名称不能为空！");
            }
            JsonResult<DepartmentVO> departmentJsonResult = userClient.getDepartmentByName(departmentName,null,companyJsonResult.getData().getId());
            if(departmentJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) + "该部门:"+departmentName+"数据不存在！");
            }

            String postName = jsonObj.getString("postName");
            if(StringUtils.isEmpty(postName)){
                throw new BusinessException("第" + (i+1) +  "行岗位名称不能为空！");
            }
            JsonResult<Role> roleJsonResult = userClient.getRoleInfoByName(postName, departmentJsonResult.getData().getId(),null,null);
            if(roleJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) + "该岗位:"+postName+"数据不存在！");
            }
            String username = jsonObj.getString("username");
            if(StringUtils.isEmpty(username)){
                throw new BusinessException("第" + (i+1) +  "用户名（工号）不能为空！");
            }
            JsonResult userIsOnly = userClient.userIsOnly(username, null, null);
            if("false".equals(userIsOnly.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行用户名（工号）必须唯一，该工号：" +username+ "已存在！");
            }
            String nickname = jsonObj.getString("nickname");
            if(StringUtils.isEmpty(nickname)){
                throw new BusinessException("第" + (i+1) +  "姓名不能为空！");
            }
            String phone = jsonObj.getString("phone");
            if(StringUtils.isEmpty(phone)){
                throw new BusinessException("第" + (i+1) +  "手机号不能为空！");
            }
            JsonResult phoneIsOnly = userClient.userIsOnly(null, phone, null);
            if("false".equals(phoneIsOnly.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行手机号必须唯一，该手机号：" +phone+ "已存在！");
            }
            String sex = jsonObj.getString("sex");
            if(StringUtils.isEmpty(sex)){
                throw new BusinessException("第" + (i+1) +  "性别不能为空！");
            }
            User user = new User();
            user.setCompanyInfoId(companyJsonResult.getData().getId());
            user.setDepartmentId(departmentJsonResult.getData().getId());
            user.setPostId(roleJsonResult.getData().getId());
            user.setRoleIds(roleJsonResult.getData().getId().toString());
            user.setUsername(username);
            user.setNickname(nickname);
            user.setPhone(phone);
            user.setSex(Integer.valueOf(sex));
            user.setIsJob(User.IsJob.job);
            user.setEnterpriseCode(companyJsonResult.getData().getMark());
            JsonResult result = userClient.addUser(user);
            if (result.getCode() != Result.Code.SUCCESS.getCode()) {
                throw new BusinessException(result.getMsg());
            }
        }

    }
    //@Transactional
    @Override
    public void syncUserInfo(EnterpricceIdVO enterpricceIdVo) throws IOException {
        System.out.println("执行-------");
        SapUtils httpUtil = new SapUtils();
        String resultText = httpUtil.execImpexpPaymentService();
        System.out.println("【测试---】接口结果>>>>result:{}:"+ resultText);
        UserClient userClient = (UserClient) ApplicationContextUtil.getBean("userClientFallback");

        JSONArray jsonArray = JSON.parseArray(resultText);
        //JSONArray jsonArray = JSON.parseArray("[{\"loginid\":\"940122\",\"jobtitle\":\"4457\",\"jobtitlename\":\"EDM技工\",\"departmentname\":\"CE事业单位一加工组\",\"departmentid\":\"631\",\"sex\":\"男\",\"mobile\":\"13168168861\",\"id\":\"23745\",\"lastname\":\"陈坤辉\",\"status\":\"1\"}]\n");
        for(int i = 0; i < jsonArray.size(); i++){
            User user = new User();
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            String loginid = jsonObj.getString("loginid");
            String departmentname = jsonObj.getString("departmentname");
            String jobtitlename = jsonObj.getString("jobtitlename");
            Long jobtitle = Long.valueOf(jsonObj.getString("jobtitle"));
            Long departmentid = Long.valueOf(jsonObj.getString("departmentid"));
            String mobile = jsonObj.getString("mobile");
            Long userid = Long.valueOf(jsonObj.getString("id"));
            String lastname = jsonObj.getString("lastname");
            String sex = jsonObj.getString("sex");
            Integer status = Integer.valueOf(jsonObj.getString("status"));
            JsonResult<User> oldUserJsonResult = userClient.getUserByUserName(loginid);
            User oldUser = oldUserJsonResult.getData();
            //User oldUser = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginid));

            //查询刀具柜系统用户的部门岗位
            JsonResult<UserVO> userVO = userClient.getUserInfoByUserName(loginid);
            if(null != oldUser){
               /* user.setThirdPartyDepartmentId(departmentid);
                user.setThirdPartyUserId(userid);*/
               /* oldUser.setThirdPartyDepartmentId(departmentid);
                oldUser.setThirdPartyJobtitleId(jobtitle);*/
                if(sex.equals("男")){
                    oldUser.setSex(1);
                }else{
                    oldUser.setSex(0);
                }
                oldUser.setThirdPartyUserId(userid);
                oldUser.setNickname(lastname);
                oldUser.setUsername(loginid);
                oldUser.setPhone(mobile);
                oldUser.setStatus(status);
                //先根据东江部门id查询
                JsonResult<DepartmentVO> departmentById = userClient.getDepartmentByName(null,departmentid,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                if(departmentById.getData().getId() > 0){
                    if(departmentid != oldUser.getThirdPartyDepartmentId()){
                        oldUser.setDepartmentId(departmentById.getData().getId());
                        oldUser.setThirdPartyDepartmentId(departmentid);
                    }
                    //部门存在的情况下 查询当前部门下有没有这个岗位
                    JsonResult<Role> roleInfoVO = userClient.getRoleInfoByName(jobtitlename,departmentById.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                    if(roleInfoVO.getData().getId() == null){
                        Role role = new Role();
                        role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        role.setDepartmentId(departmentById.getData().getId());
                        role.setThirdPartyDepartmentId(departmentid);
                        role.setThirdPartyJobtitleId(jobtitle);
                        role.setName(jobtitlename);
                        role.setCode(jobtitle.toString());
                        userClient.roleAdd(role);
                        JsonResult<Role> addRoleInfoVO =  userClient.getRoleInfoByName(jobtitlename,departmentById.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        oldUser.setPostId(addRoleInfoVO.getData().getId());
                        oldUser.setRoleIds(addRoleInfoVO.getData().getId().toString());
                        oldUser.setThirdPartyJobtitleId(addRoleInfoVO.getData().getThirdPartyJobtitleId());
                    }else{
                        oldUser.setPostId(roleInfoVO.getData().getId());
                        oldUser.setRoleIds(roleInfoVO.getData().getId().toString());
                        oldUser.setThirdPartyJobtitleId(roleInfoVO.getData().getThirdPartyJobtitleId());
                        Role role = new Role();
                        role.setId(roleInfoVO.getData().getId());
                        role.setDepartmentId(departmentById.getData().getId());
                        role.setThirdPartyDepartmentId(departmentid);
                        role.setThirdPartyJobtitleId(jobtitle);
                        role.setName(jobtitlename);
                        role.setCode(jobtitle.toString());
                        role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        userClient.updateRole(role);
                    }
                }else{
                    //对比东江系统的部门数据，不存在就新增，不同时就修改，取东江系统的部门
                    JsonResult<DepartmentVO> department = userClient.getDepartmentByName(departmentname,null,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                    if(department.getData().getId() == 0){
                        DepartmentForm departmentForm = new DepartmentForm();
                        departmentForm.setName(departmentname);
                        departmentForm.setCode(departmentid.toString());
                        departmentForm.setThirdPartyDepartmentId(departmentid);
                        departmentForm.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        //departmentForm.setCostCenter();
                        userClient.addDepartment(departmentForm);
                        JsonResult<DepartmentVO> departmentVO = userClient.getDepartmentByName(departmentname,null,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        oldUser.setDepartmentId(departmentVO.getData().getId());
                        oldUser.setThirdPartyDepartmentId(departmentid);
                        //部门不存在的情况下，岗位直接新增
                        Role role = new Role();
                        role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        role.setDepartmentId(departmentVO.getData().getId());
                        role.setThirdPartyDepartmentId(departmentid);
                        role.setThirdPartyJobtitleId(jobtitle);
                        role.setName(jobtitlename);
                        role.setCode(jobtitle.toString());
                        userClient.roleAdd(role);
                        JsonResult<Role> roleInfo = userClient.getRoleInfoByName(jobtitlename, departmentVO.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        if(roleInfo.getData().getId() == null){
                            throw new BusinessException("部门名称"+ departmentname +"--角色名称" + jobtitlename +  "--部门id-" + departmentVO.getData().getId());
                        }
                        oldUser.setPostId(roleInfo.getData().getId());
                        oldUser.setRoleIds(roleInfo.getData().getId().toString());
                        oldUser.setThirdPartyJobtitleId(roleInfo.getData().getThirdPartyJobtitleId());
                    }else{
                        if(departmentid != oldUser.getThirdPartyDepartmentId()){
                            oldUser.setDepartmentId(departmentById.getData().getId());
                            oldUser.setThirdPartyDepartmentId(departmentid);
                        }
                        DepartmentForm departmentForm = new DepartmentForm();
                        departmentForm.setId(department.getData().getId());
                        departmentForm.setName(departmentname);
                        departmentForm.setCode(departmentid.toString());
                        departmentForm.setThirdPartyDepartmentId(departmentid);
                        departmentForm.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        userClient.updateDepartment(departmentForm);
                        /*if(!departmentname.equals(userVO.getData().getDepartmentName())){
                            oldUser.setDepartmentId(department.getData().getId());
                        }*/
                        //部门存在的情况下 查询当前部门下有没有这个岗位
                        JsonResult<Role> roleInfoVO = userClient.getRoleInfoByName(jobtitlename, department.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        if(roleInfoVO.getData().getId() == null){
                            Role role = new Role();
                            role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                            role.setDepartmentId(department.getData().getId());
                            role.setThirdPartyDepartmentId(departmentid);
                            role.setName(jobtitlename);
                            role.setCode(jobtitle.toString());
                            userClient.roleAdd(role);
                            JsonResult<Role> addRoleInfoVO = userClient.getRoleInfoByName(jobtitlename, department.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                            oldUser.setPostId(addRoleInfoVO.getData().getId());
                            oldUser.setRoleIds(addRoleInfoVO.getData().getId().toString());
                            oldUser.setThirdPartyJobtitleId(addRoleInfoVO.getData().getThirdPartyJobtitleId());
                        }else{
                            oldUser.setPostId(roleInfoVO.getData().getId());
                            oldUser.setRoleIds(roleInfoVO.getData().getId().toString());
                            oldUser.setThirdPartyJobtitleId(roleInfoVO.getData().getThirdPartyJobtitleId());
                            Role role = new Role();
                            role.setId(roleInfoVO.getData().getId());
                            role.setDepartmentId(department.getData().getId());
                            role.setThirdPartyDepartmentId(departmentid);
                            role.setThirdPartyJobtitleId(jobtitle);
                            role.setName(jobtitlename);
                            role.setCode(jobtitle.toString());
                            role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                            userClient.updateRole(role);
                        }

                    }
                }


                        JsonResult updateUser = userClient.updateUser(oldUser);
                        /*if (updateUser.getCode() != Result.Code.SUCCESS.getCode()) {
                            throw new BusinessException(updateUser.getMsg());
                        }*/
            }else{
                user.setThirdPartyDepartmentId(departmentid);
                user.setThirdPartyUserId(userid);
                user.setThirdPartyJobtitleId(jobtitle);
                user.setNickname(lastname);
                user.setUsername(loginid);
                user.setPhone(mobile);
                user.setStatus(status);
                if(sex.equals("男")){
                    user.setSex(1);
                }else{
                    user.setSex(0);
                }
                user.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                //先根据东江部门id查询
                JsonResult<DepartmentVO> departmentById = userClient.getDepartmentByName(null,departmentid,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                if(departmentById.getData().getId() > 0){

                    user.setDepartmentId(departmentById.getData().getId());
                    user.setThirdPartyDepartmentId(departmentid);

                    //部门存在的情况下 查询当前部门下有没有这个岗位
                    JsonResult<Role> roleInfoVO = userClient.getRoleInfoByName(null,departmentById.getData().getId(),jobtitle, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                    if(roleInfoVO.getData().getId() == null){
                        Role role = new Role();
                        role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        role.setDepartmentId(departmentById.getData().getId());
                        role.setThirdPartyDepartmentId(departmentid);
                        role.setThirdPartyJobtitleId(jobtitle);
                        role.setName(jobtitlename);
                        role.setCode(jobtitle.toString());
                        userClient.roleAdd(role);
                        JsonResult<Role> addRoleInfoVO =  userClient.getRoleInfoByName(null,departmentById.getData().getId(),jobtitle, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        user.setPostId(addRoleInfoVO.getData().getId());
                        user.setRoleIds(addRoleInfoVO.getData().getId().toString());
                        user.setThirdPartyJobtitleId(addRoleInfoVO.getData().getThirdPartyJobtitleId());
                    }else{
                        user.setPostId(roleInfoVO.getData().getId());
                        user.setRoleIds(roleInfoVO.getData().getId().toString());
                        user.setThirdPartyJobtitleId(roleInfoVO.getData().getThirdPartyJobtitleId());
                    }
                }else{
                    //根据东江系统传过来的部门名称查询刀柜系统是否存在
                    JsonResult<DepartmentVO> department2 = userClient.getDepartmentByName(departmentname,null,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                    if(department2.getData().getId() == 0){
                        DepartmentForm departmentForm = new DepartmentForm();
                        departmentForm.setName(departmentname);
                        departmentForm.setCode(departmentid.toString());
                        departmentForm.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        departmentForm.setThirdPartyDepartmentId(departmentid);
                        userClient.addDepartment(departmentForm);
                        JsonResult<DepartmentVO> departmentInfo = userClient.getDepartmentByName(departmentname,null,Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        user.setDepartmentId(departmentInfo.getData().getId());
                        user.setThirdPartyDepartmentId(departmentid);
                        //部门不存在 直接添加岗位
                        Role role = new Role();
                        role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        role.setDepartmentId(departmentInfo.getData().getId());
                        role.setThirdPartyDepartmentId(departmentid);
                        role.setThirdPartyJobtitleId(jobtitle);
                        role.setName(jobtitlename);
                        role.setCode(jobtitle.toString());
                        userClient.roleAdd(role);
                        JsonResult<Role> serviceOne = userClient.getRoleInfoByName(jobtitlename, departmentInfo.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        user.setPostId(serviceOne.getData().getId());
                        user.setRoleIds(serviceOne.getData().getId().toString());
                        user.setThirdPartyJobtitleId(serviceOne.getData().getThirdPartyJobtitleId());
                    }else{
                        user.setDepartmentId(department2.getData().getId());
                        //部门存在 查询岗位是否存在
                        JsonResult<Role> serviceOne = userClient.getRoleInfoByName(jobtitlename, department2.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                        if(serviceOne.getData().getId() == null){
                            Role role = new Role();
                            role.setCompanyInfoId(Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                            role.setDepartmentId(department2.getData().getId());
                            role.setThirdPartyDepartmentId(departmentid);
                            role.setName(jobtitlename);
                            role.setCode(jobtitle.toString());
                            userClient.roleAdd(role);
                            JsonResult<Role> serviceOneInfo = userClient.getRoleInfoByName(jobtitlename, department2.getData().getId(),null, Long.valueOf(enterpricceIdVo.getEnterpriseId()));
                            user.setPostId(serviceOneInfo.getData().getId());
                            user.setRoleIds(serviceOneInfo.getData().getId().toString());
                            user.setThirdPartyJobtitleId(serviceOneInfo.getData().getThirdPartyJobtitleId());
                        }else{
                            user.setPostId(serviceOne.getData().getId());
                            user.setRoleIds(serviceOne.getData().getId().toString());
                            user.setThirdPartyJobtitleId(serviceOne.getData().getThirdPartyJobtitleId());
                        }
                    }
                }


                    user.setEnterpriseCode(enterpricceIdVo.getEnterpriseCode()); // 设置编码
                    JsonResult encoder = userClient.passwordEncoder("123456");
                    user.setPassword(encoder.getMsg());
                    try {
                        // 加密
                        String passwordRsa = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, DigestUtil.md5Hex("123456"));
                        user.setPasswordRsa(passwordRsa);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    JsonResult addUser = userClient.addUser(user);
                    if (addUser.getCode() != Result.Code.SUCCESS.getCode()) {
                        //throw new BusinessException(addUser.getMsg());
                    }



            }

        }
    }

    public static void main(String[] args) {
        String desSign = DigestUtil.md5Hex("123456");
        String desSign2= DigestUtil.md5Hex("companyName" +"departmentName" +"postName" +"username" + desSign);
        System.out.println(desSign);
        System.out.println(desSign2);
    }
}
